<template>
  <view class="container" style="padding-bottom: 120rpx;">
    <u--form>
      <u-form-item label="箱码" prop="containerCode" labelWidth="120rpx">
        <u--input
          placeholder="请扫码箱码"
          v-model.number="query.containerCode"
          suffixIcon="scan"
          suffixIconStyle="font-size: 68rpx"
          style="flex: 1;"
        >
        </u--input>
      </u-form-item>
			<u-form-item label="料号" prop="materialCode" labelWidth="120rpx">
			  <u--input
			    placeholder="请扫码料号"
			    v-model.number="query.materialCode"
			    style="flex: 1;"
			  >
			  </u--input>
				<u-button type="primary" style="width: 180rpx;margin-left: 10rpx;" size="medium" :disabled="!query.materialCode" @click="getMaterialInfo">查询物料</u-button>
			</u-form-item>
    </u--form>
    <!-- 扫描结果展示区域 -->
    <uni-card v-if="Object.keys(materialInfo).length > 0" title="物料信息">
      <view class="info-grid">
        <view class="info-item">
          <view class="info-label">料号</view>
          <view class="info-value">{{ materialInfo.materialCode || '-' }}</view>
        </view>
				<!-- 可编辑：数量 -->
				<view class="info-item editable-item">
				  <view class="info-label">
				    数量
				    <span class="editable-tag">可编辑</span>
				  </view>
				  <u--input
				    class="editable-input"
				    type="number"
				    v-model.number="materialInfo.qty"
				    placeholder="请输入数量"
				  ></u--input>
				</view>
				<!-- 可编辑：刃高 -->
				<view class="info-item editable-item">
				  <view class="info-label">
				    刃高
				    <span class="editable-tag">可编辑</span>
				  </view>
				  <u--input
				    class="editable-input"
				    type="number"
				    v-model.number="materialInfo.bladeHeight"
				    placeholder="请输入刃高"
				  ></u--input>
				</view>
				<!-- 可编辑：胶条截面 -->
				<view class="info-item editable-item">
				  <view class="info-label">
				    胶条截面
				    <span class="editable-tag">可编辑</span>
				  </view>
				  <u--input
				    class="editable-input"
				    v-model="materialInfo.sealCross"
				    placeholder="请输入胶条截面"
				  ></u--input>
				</view>
				<view class="info-item editable-item">
				  <view class="info-label">
				    品种
				    <span class="editable-tag">可编辑</span>
				  </view>
					<uni-data-select
						:clear="false"
						v-model="materialInfo.status"
						:localdata="dict.semi_material_status"
						placeholder="请选择品种"
					></uni-data-select>
				</view>
				<!-- 可编辑：生产日期 -->
				<view class="info-item editable-item">
				  <view class="info-label">
				    生产日期
				    <span class="editable-tag">可编辑</span>
				  </view>
				  <u--input
				    class="editable-input"
				    v-model="materialInfo.productionDate"
				    placeholder="请选择生产日期"
				    @focus="show = true"
				  ></u--input>
					<u-datetime-picker
						:show="show"
						v-model="pickTime"
						mode="datetime"
						@confirm="selectTime"
						@change="changeLog($event)"
						@cancel="show = false"
					></u-datetime-picker>
				</view>
        <view class="info-item">
          <view class="info-label">批号</view>
          <view class="info-value">{{ materialInfo.materialBatch || '-' }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">冻结状态</view>
          <view class="info-value">{{ dict.text.semi_frozen[materialInfo.frozenStatus] || '-' }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">物料状态</view>
          <view class="info-value">{{ dict.text.semi_material_status[materialInfo.status] || '-' }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">入库时间</view>
          <view class="info-value">{{ materialInfo.boxInboundTime || '-' }}</view>
        </view>
      </view>
    </uni-card>
    <u-toast ref="uToast"></u-toast>
    <view class="commonButton">
      <u-button type="primary" :disabled="!query.containerCode || Object.keys(materialInfo).length === 0" @click="confirmBind">确认绑定</u-button>
    </view>
  </view>
</template>

<script>
	import { getMaterialInfoAPI, ncmmBindInAPI } from '@/api/work/ncmm'
	import uniDataSelect from '../../../node_modules/@dcloudio/uni-ui/lib/uni-data-select/uni-data-select.vue'
	import {
		uniCard,
		uniTable,
		uniTr,
		uniTd,
		uniTh,
		uniDatetimePicker
	} from '@dcloudio/uni-ui'
	export default {
		components: {
			uniCard,
			uniTable,
			uniTr,
			uniTd,
			uniTh,
			uniDataSelect,
			uniDatetimePicker
		},
		dicts: ['semi_material_status', 'semi_frozen'],
		data() {
			return {
				query: {
					containerCode: '',
					materialCode: ''
				},
				materialInfo: {},
				show: false,
				pickTime: Number(new Date())
			};
		},
		onLoad() {
			uni.$on('scancodedate',(data) => this.getCode(data.code))
		},  
		onUnload() {    
			uni.$off('scancodedate')
		},
		methods: {
			async getCode(code) {
				const regex = /^R-\d+$/
				if (regex.test(code)) {
					this.query.containerCode = code
				} else {
					return this.$refs.uToast.show({
						type: 'warning',
						message: '请扫描正确的二维码'
					})
				}
			},
			validateForm() {
			  const requiredFields = [
			    { field: 'qty', message: '请输入数量' },
			    { field: 'bladeHeight', message: '请输入刃高' },
			    { field: 'sealCross', message: '请输入胶条截面' },
			    { field: 'status', message: '请选择品种' },
			    { field: 'productionDate', message: '请选择生产日期' }
			  ]
			  for (const { field, message } of requiredFields) {
			    const value = this.materialInfo[field];
			    // 检查值是否为空（考虑0是有效的数量）
			    if (value === undefined || value === null || value === '') {
			      this.$refs.uToast.show({
							type: 'warning',
							message
						})
			      return false
			    }
			  }
			  return true
			},
			formatDate(timestamp) {
				const date = new Date(timestamp)
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				const hours = String(date.getHours()).padStart(2, '0')
				const minutes = String(date.getMinutes()).padStart(2, '0')
				const seconds = String(date.getSeconds()).padStart(2, '0')
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
			},
			selectTime() {
				const formatDate = this.formatDate(this.pickTime)
				this.materialInfo.productionDate = formatDate
				this.show = false
			},
			changeLog(e) {
				this.pickTime = Number(e.value)
			},
			async getMaterialInfo() {
				const res = await getMaterialInfoAPI({
					materialCode: this.query.materialCode
				})
				if (res.code === 200) {
					// 接口返回数据覆盖默认值
					this.materialInfo = res.data
					this.materialInfo.status = String(this.materialInfo.status)
					console.log(typeof this.materialInfo.status)
				} else {
					this.query.materialCode = '' // 修复原代码中的变量名错误
					return this.$refs.uToast.show({
						type: 'warning',
						message: res.message
					})
				}
			},
			async confirmBind() {
				if (!this.validateForm()) {
					return
				}
				const submitForm = {
					containerCode: this.query.containerCode,
					...this.materialInfo
				}
				const res = await ncmmBindInAPI(submitForm)
				// console.log(res)
				if (res.code === 200) {
					this.$refs.uToast.show({
						type: 'success',
						message: res.message
					})
					// 重置表单
					this.query.containerCode = ''
					this.materialInfo = {}
				} else {
					return this.$refs.uToast.show({
						type: 'warning',
						message: res.message
					})
				}
			}
		}
	}
</script>

<style lang="scss">
.info-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  margin-top: 10rpx;
}

.info-item {
  width: 100%;
  padding: 15rpx;
  background-color: #f5f7fa;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
}

.info-label {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 5rpx;
  display: flex;
  align-items: center;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  line-height: 40rpx;
}

/* 可编辑项特殊样式 */
.editable-item {
  background-color: #f0f7ff; /* 浅蓝色背景区分 */
  border: 1px dashed #409eff; /* 蓝色虚线边框 */
}

/* 可编辑标签 */
.editable-tag {
  margin-left: 10rpx;
  font-size: 20rpx;
  padding: 2rpx 10rpx;
  background-color: #409eff;
  color: white;
  border-radius: 4rpx;
}

/* 可编辑输入框样式：增强区分度 */
.editable-input {
  font-size: 28rpx !important;
  color: #1890ff !important; /* 蓝色文字区分 */
  font-weight: 500 !important;
  padding: 5rpx 0 !important;
  background: transparent !important;
  border: 1px solid transparent !important;
  line-height: 40rpx !important;
  
  /* 聚焦时明显提示 */
  &:focus {
    border-bottom: 1px solid #1890ff !important;
    border-radius: 0 !important;
    box-shadow: 0 1px 3px rgba(24, 144, 255, 0.2) !important;
  }
}

/* 输入框后缀单位样式 */
.u-input__suffix {
  font-size: 28rpx !important;
  color: #333 !important;
  font-weight: 500 !important;
}

.uni-card {
	margin: 0 !important;
}

/* 提交按钮添加加载状态样式 */
// .commonButton {
//   position: relative;
// }

.u-button--loading {
  opacity: 0.8;
}
</style>